using System;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.Linq;
using Azure.Domain.Models;
using Azure.Infrastructure;
using Microsoft.WindowsAzure.StorageClient;

namespace Azure.Membership
{
    public interface IMembershipRepository
    {
        User LoadByEmail(string email);
        User LoadByUsername(string username);
        void Create(User user);
    }

    public class MembershipRepository : IMembershipRepository
    {
        private readonly IRepository<User> _repository;
        public MembershipRepository(IRepository<User> repository)
        {
            _repository = repository;
        }

        public User LoadByEmail(string email)
        {
            var usersLinqQuery = from u in _repository.Table where u.Email == email select u;
            var query = usersLinqQuery.AsTableServiceQuery();
            var users = query.Execute();
            return GetUser(users);
        }

        public User LoadByUsername(string username)
        {
            var usersLinqQuery = from u in _repository.Table where u.PartitionKey == username && u.UserName == username select u;
            var query = usersLinqQuery.AsTableServiceQuery();
            var users = query.Execute();

            return GetUser(users);
        }

        private User GetUser(IEnumerable<User> users)
        {
            User result = null;
            var enumerator = users.GetEnumerator();
            try
            {
                if (enumerator != null && enumerator.MoveNext())
                {
                    result = enumerator.Current;
                }
            }
            catch (DataServiceQueryException)
            {
                result = null;
            }

            return result;
        }

        public void Create(User user)
        {
            _repository.Insert(user);
        }
    }
}